<template>
	<!--  修改 消缺任务 -->
	<div>
		<div id="app" class="container">
			<!--查询模块-->
			<div class="row">
				<div class="col-12 text-right">
					<form class="form-group form-inline justify-content-end">
						<div class="row mb-12">
							<div class="col-md-4">
								<span>任务编号</span>
								<input class="form-control" v-model="updateSolvetObj.solvetaskcode" type="search"
									placeholder="请输入查询字符">
							</div>
							<div class="col-md-4">
								<span>任务名称</span>
								<input class="form-control" v-model="updateSolvetObj.solvetaskname" type="search"
									placeholder="">
							</div>
							<div class="col-md-4">
								<span>工作单据</span>
								<select class="form-control" v-model="updateSolvetObj.workdoctype">
									<option value="-1" selected>--请选择--</option>
									<option v-for="item in queryByDocType" :value="item.configvalueid" :key="item.id">
										{{ item.configvaluename }}
									</option>
								</select>
							</div>

						</div>
						<div class="row mb-12">
							<div class="col-md-4">
								<span>任务负责人</span>
								<select class="form-control" v-model="selectedUser">
									<option value="-1" selected>--请选择--</option>
									<option v-for="item in queryByRoleName" :value="item.usercode" :key="item.id">
										{{ item.username }}
									</option>
								</select>
							</div>
							<div class="col-md-4">
								<span>下发人:</span>
								<span class="form-control" v-model="updateSolvetObj.issuedbyname"
									style="color: gray;">admin</span>
							</div>
							<div class="col-md-4">
								<span>下发时间</span>
								<el-date-picker v-model="updateSolvetObj.issuedtime" type="date"
									value-format="yyyy-MM-dd" placeholder="选择日期">
								</el-date-picker>
							</div>
						</div>
						<div class="row mb-12">

							<div class="col-md-4">
								<span>任务描述</span>
								<textarea class="form-control" v-model="updateSolvetObj.taskdesc" rows="3"></textarea>
							</div>
							<div class="col-md-4">
								<span>备注</span>
								<textarea class="form-control" v-model="updateSolvetObj.common" rows="3"></textarea>
							</div>
							<div class="col-md-4">
								<span>消缺员</span><span style="text-decoration: line-through;color: red;"><a href="#"
										style="color: red;" @click="showModalTf">-点击选择-</a></span>
								<textarea class="form-control" v-model="value" rows="3"></textarea>

								<div>
									<el-dialog title="选择消缺员" :visible.sync="modalTfVisible" width="50%"
										:before-close="handleCloseTf">
										<el-transfer v-model="value" :props="{
													  id:'id',
											          key: 'solvercode',
											          label: 'solvername'
											        }" :titles="['待选消缺员', '已选消缺员']" :data="TransferList">
										</el-transfer>

										<span slot="footer" class="dialog-footer">
											<el-button @click="handleClose">取消</el-button>
											<el-button type="primary" @click="handleSaveTf()">保存</el-button>
										</span>
									</el-dialog>
								</div>
							</div>
						</div>
						<div class="row mb-12">

							<div class="col">
								<span>缺陷列表:</span>
								<button type="button" class="btn btn-outline-primary" @click="showModal">+添加缺陷</button>
								<div>
									<el-dialog title="选择缺陷" :visible.sync="modalVisible" width="50%"
										:before-close="handleClose">
										<table class="table table-striped table-hover table-bordered center">
											<thead>
												<tr>
													<td><input type="checkbox" id="boxMax" v-model="isAllSelected"
															@change="toggleAllSelection" />选择</td>
													<td v-text="'线路编号'"></td>
													<td v-text="'杆塔编号'"></td>
													<td v-text="'缺陷等级'"></td>
													<td v-text="'缺陷类型'"></td>
													<td v-text="'发现人'"></td>
													<td v-text="'缺陷描述'"></td>
													<td v-text="'发现时间'"></td>
												</tr>
											</thead>
											<tbody v-if="listInTaDe.length!=null && listInTaDe.length!=''">
												<tr v-for="item in listInTaDe">
													<td><input type="checkbox" v-model="item.selected"
															class="checkBox" /></td>
													<td v-text="item.id" hidden></td>
													<td v-text="item.linecode"></td>
													<td v-text="item.polecode"></td>
													<td v-text="item.buglevelname"></td>
													<td v-text="item.bugtypename"></td>
													<td v-text="item.discoverername"></td>
													<td v-text="item.bugdesc"></td>
													<td v-text="item.discovertime"></td>
												</tr>

											</tbody>
											<tbody v-else>
												<tr>
													<td colspan="9">暂无缺陷数据！！！</td>
												</tr>

											</tbody>

										</table>
										<!--分页-->
										<!--显示分页信息-->
										<div class="row  text-right">
											<!--文字信息-->
											<div class="col-md-6">
												当前第 <input name="startPage" :value="pageInfoInTaDe.pageNum"
													style="width: 20px" />/{{pageInfoInTaDe.pages}}页.一共
												{{pageInfoInTaDe.total}}条记录
											</div>
											<!--点击分页-->
											<div class="col-md-6">
												<nav aria-label="Page navigation example">
													<ul class="pagination">
														<li class="page-item"><a class="page-link" href="javascript:;"
																@click="pageInfoInTaDe.pageNum=1;IsTaDe()">首页</a></li>
														<li class="page-item"
															:class="{'disabled':!pageInfoInTaDe.hasPreviousPage}">
															<a class="page-link" href="javascript:;"
																@click="pageInfoInTaDe.pageNum=pageInfoInTaDe.pageNum-1;IsTaDe()"
																aria-label="Previous">
																<span aria-hidden="true">&laquo;</span>
															</a>
														</li>
														<li class="page-item"
															v-for="p in pageInfoInTaDe.navigatepageNums"
															:class="{'active':pageInfoInTaDe.pageNum==p}"><a
																class="page-link" href="javascript:;"
																@click="pageInfoInTaDe.pageNum=p;IsTaDe()"
																v-text="p"></a></li>
														<li class="page-item"
															:class="{'disabled':!pageInfoInTaDe.hasNextPage}">
															<a class="page-link" href="javascript:;"
																@click="pageInfoInTaDe.pageNum=pageInfoInTaDe.pageNum-0+1;IsTaDe()"
																aria-label="Next">
																<span aria-hidden="true">&raquo;</span>
															</a>
														</li>
														<li class="page-item"><a class="page-link" href="javascript:;"
																@click="pageInfoInTaDe.pageNum=pageInfoInTaDe.pages;IsTaDe()">尾页</a>
														</li>
													</ul>
												</nav>
											</div>
										</div>
										<!--分页结束-->
										<span slot="footer" class="dialog-footer">
											<el-button @click="handleClose">取消</el-button>
											<el-button type="primary" @click="handleSave"
												v-if="listInTaDe.length!=null && listInTaDe.length!=''">保存</el-button>
										</span>
									</el-dialog>
								</div>
							</div>
						</div>
					</form>

				</div>
			</div> <!--查询模块结束-->
			<table class="table table-striped table-hover table-bordered center">
				<thead>
					<tr>
						<td v-text="'线路编号'"></td>
						<td v-text="'杆塔编号'"></td>
						<td v-text="'缺陷等级'"></td>
						<td v-text="'缺陷类型'"></td>
						<td v-text="'缺陷描述'"></td>
						<td v-text="'发现人'"></td>
						<td v-text="'发现时间'"></td>
						<td>操作</td>
					</tr>
				</thead>
				<tbody >
					<tr v-if="list.length>0" v-for="i in list">
						<td>{{ i.linecode }}</td>
						<td>{{ i.polecode }}</td>
						<td>{{ i.buglevelname }}</td>
						<td>{{ i.bugtypename }}</td>
						<td>{{ i.discoverername }}</td>
						<td>{{ i.bugdesc }}</td>
						<td>{{ i.discovertime }}</td>
						<td>
							<div>
								<button type="button" class="btn btn-outline-primary"
									@click="removeItemlistSode(i)">移除</button>
							</div>
						</td>
					</tr>


					<tr v-if="list.length==0">
						<td colspan="9">
							<div>
								没有缺陷数据，请<a href="#" @click="showModal">选择</a>
							</div>
						</td>
					</tr>

				</tbody>



			</table>
			<div>
				<button type="button" class="btn btn-primary me-3" @click="save">保存</button>
				<button type="button" class="btn btn-secondary" @click="$router.go(-1)">返回</button>
			</div>

			<!--分页-->
			<!--显示分页信息-->

			<!--分页结束-->
		</div>
	</div>
</template>

<script>
	import {
		lib
	} from 'crypto-js/core'
	import {
		psSolvetaskMain,
		queryBySolvetaskStatus,
		queryBySolver,
		queryByDocType,
		queryByRoleName,
		addPsSolvetaskMain,
		updateSolverDetail,
		InspectiontaskDetail,
		addPsSolvetaskDetail,
		updatepsSolvetaskMain,
		queryByListl,
		queryIntaDeByObj,
		deleteByIdsObj
	} from '../../config/request.js'
	export default {
		data() {
			return {
				updateSolvetObj: {
					// 修改 对象
				},
				addSolvetObj: {
					workdoctype: '-1',
					taskstatus: '-1',
					issuedbycode: '下发人code', // 下发人code 当前登录用户
					issuedbyname: 'admin', // 下发人name     当前登录用户
					taskstatusname: '待分配', // 任务状态名称
					taskstatus: 1, //任务状态id

				}, // 添加对象
				psSystemconfig: {}, //消缺任务状态 下拉框数据
				list: [], // 获取 缺陷 后 的存储
				modalVisible: false, // 控制模态框显示隐藏
				incode: 0, // 消缺任务编号
				inid: 0, // 消缺任务id
				value: [], // 双向绑定的值
				TransferList: [], // Transfer 数据源
				modalTfVisible: false, // 控制模态框显示隐藏
				SolvetDetailObj: {},
				queryByDetail: {}, // 存储 选中的 消缺员
				queryByDocType: {}, // 工作单据类型 状态
				queryByRoleName: {}, //线路管理员 下拉框数据
				selectedUser: '-1', // 任务负责人
				updateSolverDetail: {}, //修改(分配) 消缺 信息
				listInTaDe: [],
				pageInfoInTaDe: {},
				InspectiontaskDetailObj: {}, // 巡检任务子表 未消缺的任务
				isAllSelected: false, // 全选按钮 是否选中
				addPsSolvetaskDetailObj: {}, // 添加 消缺 任务子表 对象
				listSode: false, // 判断当前 是否有 再消缺任务子表中存在
				listInTaDeSode: [], //根据 消缺任务子表 去查询 巡检任务子表 数据
				deleteObj: {}, // 删除 对象
			}
		},
		methods: {
			load() {

				queryByDocType().then(json => {
					this.queryByDocType = json.data.queryByDocType
				})

				queryByRoleName().then(json => {
					this.queryByRoleName = json.data.queryByRoleName
				})



				this.IsTaDe()

			},
			IsTaDe() {
				this.InspectiontaskDetailObj.pageNum = this.pageInfoInTaDe.pageNum;
				InspectiontaskDetail(this.InspectiontaskDetailObj).then(json => {
					this.pageInfoInTaDe = json.data.pageInfo;
					this.listInTaDe = json.data.pageInfo.list;
				})
			},
			save() {
				// 提交 保存
				if (this.selectedUser != -1) {
					//线路管理员
					const selectedItem = this.queryByRoleName.find(item => item.usercode === this.selectedUser);
					console.log("选中的项为: ", selectedItem);
					this.updateSolvetObj.taskmanagercode = selectedItem.usercode
					this.updateSolvetObj.taskmanagername = selectedItem.username
				}

				if (this.updateSolvetObj.workdoctype != -1) {
					//工作单据类型
					const selectedItems = this.queryByDocType.find(item => item.configvalueid === this.updateSolvetObj
						.workdoctype);
					console.log("选中的项为: ", selectedItems);
					this.updateSolvetObj.workDocType = selectedItems.configvalueid
					this.updateSolvetObj.workdoctypename = selectedItems.configvaluename
				}

				if (Object.keys(this.queryByDetail).length > 0) {
					this.updateSolvetObj.taskstatus = 2
					this.updateSolvetObj.taskstatusname = '已分配'

					//  选中 消缺 员
					this.queryByDetail.forEach(item => {
						this.updateSolverDetail.taskid = this.updateSolvetObj.solvetaskcode
						this.updateSolverDetail.id = item.id
						console.log(this.updateSolverDetail)

						updateSolverDetail(this.updateSolverDetail).then(json => {

						})
						/* // 延迟一秒后执行销毁操作
						setTimeout(() => {
							this.$destroy(); // 销毁组件实例
						}, 1000); // 延迟 1000 毫秒（即 1 秒） */

					})
				}

				if (this.list.length != 0) {
					console.log(this.list)
					this.updateSolvetObj.iscancel = 0
					this.updateSolvetObj.createdby = this.updateSolvetObj.issuedbycode
					this.getCurrentDate()

					// 修改 消缺 任务 
					updatepsSolvetaskMain(this.updateSolvetObj).then(json => {
						alert(json.message)

					})

				} else {
					alert("请添加缺陷！！！")
				}

			},
			showModal() {
				// 模态框
				this.modalVisible = true;
			},
			handleClose() {
				// 模态框
				// 可以在这里进行取消操作
				this.modalVisible = false;
			},
			removeItemlistSode(item) {
				
				const flag = confirm("确定要移除吗？");
				if (flag) {
					this.deleteObj.taskid = this.updateSolvetObj.solvetaskcode;
					this.deleteObj.inspectiontaskdelid = item.id;
					deleteByIdsObj(this.deleteObj)
						.then(json => {
							
							 // 从数组中移除对象
							       this.list = this.list.filter(subArray => {
							            // 在每个子数组中查找要删除的对象
							            return subArray.id !== item.id;
							          });
							
							        
							this.IsTaDe();
						})
						.catch(error => {
							console.error("删除失败:", error);
						});

					console.log(this.listInTaDeSode);

				}
			},
			handleSave() {
				// 模态款的添加缺陷的 保存按钮
				const selectedItems = this.listInTaDe.filter(item => item.selected);
				console.log(JSON.stringify(selectedItems))
				// 检查 this.list 中是否已经存在当前选中的项目
				const existingItems = this.list.filter(item => {
					return selectedItems.some(selected => selected.id === item.id);
				});
				
				// 如果不存在,才将选中的项目添加到 this.list 中
				if (existingItems.length === 0) {
					this.list.push(...selectedItems);
					// 根据 缺陷 编号  创建 消缺任务子表
					 this.list = this.list.filter(item => item !== null);
					 this.list.forEach(item => {
						if(item!==null){
							if (this.listInTaDeSode.some(sodeItem => {
								return sodeItem.id === item.id})) {
									//alert("存在")
								// 如果存在则不执行添加操作
								// 如果需要执行添加操作，您可以在这里添加相应的逻辑
							} else {
								//alert("不存在")
											this.addPsSolvetaskDetailObj.taskid = this.updateSolvetObj.solvetaskcode
											this.addPsSolvetaskDetailObj.inspectiontaskdelid = item.id
											this.getCurrentDate()
											this.addPsSolvetaskDetailObj.createdby = this.updateSolvetObj.issuedbyname
											addPsSolvetaskDetail(this.addPsSolvetaskDetailObj).then(json => {
												
													
											})
									
										}
								
							
						}else{
							console.log("item"+JSON.stringify(item))
						}
					})
					

				} else {
					alert("不可重复添加！")
				}
				
				this.IsTaDe()
				
				this.modalVisible = false; // 关闭对话框示例
				

			},
			toggleAllSelection() {
				// 切换全选/全不选
				this.listInTaDe.forEach(item => {
					item.selected = this.isAllSelected;
				});

			},
			// 巡检员 模态框=============
			showModalTf() {
				queryBySolver().then(json => {
					this.TransferList = json.data.queryBySolver
				})
				// 模态框
				this.modalTfVisible = true;
			},
			handleCloseTf(done) {
				// 模态框
				// 可以在这里进行取消操作
				this.modalTfVisible = false;
				done(); // 关闭模态框
			},
			handleSaveTf() {
				// 保存 transfer  的信息
				// 处理保存逻辑
				// 获取所选的 value 和 desc
				const selectedItems = this.TransferList.filter(item => this.value.includes(item.solvercode));
				console.log('保存选择的内容:', selectedItems);

				// 将选中的巡检员信息添加到数组中
				const selectedInspectors = [];
				selectedItems.forEach(item => {
					this.iname += item.inspectorname + ','
					const inspector = {
						id: item.id,
						solvercode: item.solvercode,
						solvername: item.solvername
					};
					selectedInspectors.push(inspector);
				});


				// 将选中的消缺员信息赋给 queryByDetail 对象
				this.queryByDetail = selectedInspectors;
				console.log(this.queryByDetail)
				// 将所选的 desc 值赋给 psInspectiontaskMain.issuedByName



				this.modalTfVisible = false; // 关闭模态框


			},
			getCurrentDate() {
				const date = new Date();
				const year = date.getFullYear();
				const month = ('0' + (date.getMonth() + 1)).slice(-2);
				const day = ('0' + date.getDate()).slice(-2);
				const hours = ('0' + date.getHours()).slice(-2);
				const minutes = ('0' + date.getMinutes()).slice(-2);
				const seconds = ('0' + date.getSeconds()).slice(-2);
				// 创建时间
				this.updateSolvetObj.lastupdatetime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

				this.addPsSolvetaskDetailObj.creationtime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
		},
		mounted() {
			this.load();

			this.updateSolvetObj = this.$route.query.obj;
			this.selectedUser = this.updateSolvetObj.taskmanagercode;
			queryByListl(this.updateSolvetObj.solvetaskcode).then(json => {
				if (Object.keys(json.data.objList).length > 0) {
					json.data.objList.forEach(item => {

						queryIntaDeByObj(item.inspectiontaskdelid).then(json => {
							this.list.push(...json.data.queryIntaDeByObj)
							console.log(this.list)
							this.listInTaDeSode.push(...json.data.queryIntaDeByObj)
						})

					})

					this.listSode = true;
				}

			})
		},
		created() {



		}
	}
</script>

<style>
</style>